package org.jeecg.modules.demo.stock.controller;

import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.JstlHttpUpload;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.demo.stock.entity.*;
import org.jeecg.modules.demo.stock.service.ITbStockCodeService;
import org.jeecg.modules.demo.stock.service.ITbStockKService;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;

import org.jeecg.modules.demo.stock.service.ITbStockMinuteService;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.jeecg.common.system.base.controller.JeecgController;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;
import com.alibaba.fastjson.JSON;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.jeecg.common.aspect.annotation.AutoLog;

 /**
 * @Description: 股票k线图
 * @Author: jeecg-boot
 * @Date:   2022-01-10
 * @Version: V1.0
 */
@Api(tags="股票k线图")
@RestController
@RequestMapping("/stock/tbStockK")
@Slf4j
public class TbStockKController extends JeecgController<TbStockK, ITbStockKService> {
	@Autowired
	private ITbStockKService tbStockKService;
	 //发送请求方法
	 @Autowired
	 private JstlHttpUpload jstlHttpUpload;
	 @Autowired
	 private ITbStockCodeService tbStockCodeService;

	 @Value("${jeecg.path.upload}")
	 private String upLoadPath;

	 //股票分钟交易
	 @Autowired
	 private ITbStockMinuteService tbStockMinuteService;

	/**
	 * 分页列表查询
	 *
	 * @param tbStockK
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	@AutoLog(value = "股票k线图-分页列表查询")
	@ApiOperation(value="股票k线图-分页列表查询", notes="股票k线图-分页列表查询")
	@GetMapping(value = "/list")
	public Result<?> queryPageList(TbStockK tbStockK,
								   @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
								   @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
								   HttpServletRequest req) throws ParseException {
		QueryWrapper<TbStockK> queryWrapper = QueryGenerator.initQueryWrapper(tbStockK, req.getParameterMap());
		Page<TbStockK> page = new Page<TbStockK>(pageNo, pageSize);
		IPage<TbStockK> pageList = tbStockKService.page(page, queryWrapper);
		tbStockKService.list(queryWrapper);
		List<TbStockK> records = pageList.getRecords();

		if (records!=null && !records.isEmpty()){
			for (TbStockK record : records) {
				String stockId = record.getStockId();
				TbStockCode code = tbStockCodeService.getById(stockId);
				if (code!=null){
					record.setStockName(code.getName());
				}
			}

		}

		//添加k图数据
		String remark = tbStockK.getRemark();

		if (StringUtils.isNoneBlank(remark)){
			if (StringUtils.isNoneBlank(remark)){
				tbStockKService.saveList(remark);
			}
		}
		return Result.OK(pageList);
	}

	/**
	 *   添加
	 *
	 * @param tbStockK
	 * @return
	 */
	@AutoLog(value = "股票k线图-添加")
	@ApiOperation(value="股票k线图-添加", notes="股票k线图-添加")
	@PostMapping(value = "/add")
	public Result<?> add(@RequestBody TbStockK tbStockK) {
		tbStockKService.save(tbStockK);
		return Result.OK("添加成功！");
	}

	/**
	 *  编辑
	 *
	 * @param tbStockK
	 * @return
	 */
	@AutoLog(value = "股票k线图-编辑")
	@ApiOperation(value="股票k线图-编辑", notes="股票k线图-编辑")
	@PutMapping(value = "/edit")
	public Result<?> edit(@RequestBody TbStockK tbStockK) {
		tbStockKService.updateById(tbStockK);
		return Result.OK("编辑成功!");
	}

	/**
	 *   通过id删除
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "股票k线图-通过id删除")
	@ApiOperation(value="股票k线图-通过id删除", notes="股票k线图-通过id删除")
	@DeleteMapping(value = "/delete")
	public Result<?> delete(@RequestParam(name="id",required=true) String id) {
		tbStockKService.removeById(id);
		return Result.OK("删除成功!");
	}

	/**
	 *  批量删除
	 *
	 * @param ids
	 * @return
	 */
	@AutoLog(value = "股票k线图-批量删除")
	@ApiOperation(value="股票k线图-批量删除", notes="股票k线图-批量删除")
	@DeleteMapping(value = "/deleteBatch")
	public Result<?> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
		this.tbStockKService.removeByIds(Arrays.asList(ids.split(",")));
		return Result.OK("批量删除成功!");
	}

	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "股票k线图-通过id查询")
	@ApiOperation(value="股票k线图-通过id查询", notes="股票k线图-通过id查询")
	@GetMapping(value = "/queryById")
	public Result<?> queryById(@RequestParam(name="str",required=true) String str) {

		String[] split = str.split(",");
		for (String id : split) {
			List<TbStockKVo> result = new ArrayList<>();
			TbStockK tbStockK = tbStockKService.getById(id);
			if(tbStockK==null) {
				return Result.error("未找到对应数据");
			}
			Double closing = tbStockK.getClosing();




			List<Double> list = new ArrayList<>();
			list.add(0.01);
			list.add(0.02);
			list.add(0.03);
//			list.add(0.04);
//			list.add(0.05);
//			list.add(0.06);
//			list.add(0.07);
//			list.add(0.08);
//			list.add(0.09);
//			list.add(0.10);

			int  ll = 1;
			for (Double aDouble : list) {
				double number = closing * aDouble;
				double count = closing + number;
				Double aDouble1 = Double.valueOf(String.format("%.2f", count));
				TbStockKVo vo = new TbStockKVo();
				vo.setPrice(ll++); //涨跌额
				vo.setSwing(aDouble1); //价格
				result.add(vo);
			}
			int cc =-1;
			for (Double aDouble : list) {
				double number = closing * aDouble;
				double count = closing - number;
				Double aDouble1 = Double.valueOf(String.format("%.2f", count));
				TbStockKVo vo = new TbStockKVo();
				vo.setPrice(cc--); //涨跌额
				vo.setSwing(aDouble1); //价格
				result.add(vo);
			}

			String s = JSONObject.toJSONString(result);
			System.out.println(s);

		}
		return Result.OK();
	}

    /**
    * 导出excel
    *
    * @param request
    * @param tbStockK
    */
    @RequestMapping(value = "/exportXls1")
    public ModelAndView exportXls1(HttpServletRequest request, TbStockK tbStockK) {
        return super.exportXls(request, tbStockK, TbStockK.class, "股票k线图");
    }

	 /**
	  * 导出excel
	  *
	  * @param request
	  * @param tbStockK
	  */
	 @RequestMapping(value = "/exportXls")
	 public ModelAndView exportXls(HttpServletRequest request, TbStockK tbStockK) {

		 ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());

		 String str = "603529";//603529 003032
		 String order = "asc"; // asc 升序  desc 降序
		 List<TbStockMinuteCountVo> voList = getList(str,order);
		 //根据股票编码,查询股票名称

		 //导出文件名称
		 mv.addObject(NormalExcelConstants.FILE_NAME, "全员列表");
		 mv.addObject(NormalExcelConstants.CLASS, TbStockMinuteCountVo.class);
		 LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
		 //判断是升序还是降序
		 /**
		  * DESC  -- 降序  从高到低  最大
		  */
		String orderName = "";
		 if ("asc".equals(order)){
			 orderName = "最小";
		 }else{
			 orderName = "最大";
		 }
		 ExportParams exportParams = new ExportParams(str+"列表数据", "导出人:" +orderName, "导出信息");
		 exportParams.setImageBasePath(upLoadPath);
		 mv.addObject(NormalExcelConstants.PARAMS, exportParams);
		 mv.addObject(NormalExcelConstants.DATA_LIST, voList);
		 return mv;
	 }

	 public List<TbStockMinuteCountVo> getList(String str,String order) {
		 List<TbStockMinuteCountVo> countVoList = null;
		 String[] arr = str.split(",");
		 for(String code:arr){
			 List<TbStockMinuteVo> list = tbStockMinuteService.selectList(code,order);
			 int count= 0;
			 for (TbStockMinuteVo vo : list) {
				 count++;
				 String timeId = vo.getTimeId();
				 Double value1 = vo.getValue1();
				 String dayTime = vo.getDayTime();
				 String va = "时间:"+dayTime+" 价格:"+value1;
				 boolean test = test(count);
				 if (test){
					 System.out.println(timeId);
					 System.out.println(va);
				 }else{
					 System.out.println(va);
				 }
			 }
			 //根据时间排序，从小到大
			 try {
				 countVoList = timeSort(list);
			 } catch (ParseException e) {
				 e.printStackTrace();
			 }

			 System.out.println("==========================");

		 }
		 System.out.println("结束");
		 return  countVoList;
	 }

	 //根据时间排序
	 private List<TbStockMinuteCountVo> timeSort(List<TbStockMinuteVo> list) throws ParseException {
		 /**
		  * 根据时间段分类
		  * 9:30 - 9:59
		  * 10:00-10:29
		  * 10:30-10.59
		  * 11:00-11.30
		  * 11:30
		  * 1:00-1:29
		  * 1:30-1:59
		  * 2:00-2:29
		  * 2:30-3:00
		  * 3:00
		  * 4个小时
		  */
		 SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm");
		 Date now = null;
		 int number1 = 0;
		 int number2 = 0;
		 int number3 = 0;
		 int number4 = 0;

		 int number5 = 0;
		 int number6 = 0;
		 int number7 = 0;
		 int number8 = 0;
		 List<TbStockMinuteCountVo> countVoList1 = new ArrayList<>();


		 //创建TreeSet集合对象，通过比较器排序进行排序
		 TreeSet<TbStockMinuteCountVo> countVoList = new TreeSet<TbStockMinuteCountVo>(new Comparator<TbStockMinuteCountVo>() {
			 @Override
			 public int compare(TbStockMinuteCountVo s1, TbStockMinuteCountVo s2) {
//                int num = (s2.getChinese()+s2.getMath())-(s1.getChinese()+s1.getMath());
				 //主要条件
				 int num = s2.getNumber() - s1.getNumber();
				 //次要条件
				 int num2 = num == 0 ? s1.getTop() - s2.getTop() : num;
				 return num2;
			 }
		 });

		 for (TbStockMinuteVo tbStockMinuteVo : list) {
			 String dayTime = tbStockMinuteVo.getDayTime();
			 now = formatter.parse(dayTime);
			 int hours = now.getHours();//小时
			 int minutes = now.getMinutes();//分钟
//            System.out.println(hours + " " + minutes);
			 if (hours == 9) {
				 number1++;
			 }else if (hours == 10 && minutes <= 29){
				 number2++;
			 }else if (hours == 10 && minutes >= 30){
				 number3++;
			 }else if (hours == 11){
				 number4++;
			 }else if (hours == 13 && minutes <= 29){
				 number5++;
			 }else if (hours == 13 && minutes >= 30){
				 number6++;
			 }else if (hours == 14 && minutes <= 29){
				 number7++;
			 }else if (hours == 14 && minutes >= 30 || hours == 15){
				 number8++;
			 }else{
				 System.out.println(tbStockMinuteVo);
			 }
		 }
		 DecimalFormat df=new DecimalFormat("0.00");
		 int sum = list.size();

		 /**
		  * 根据数量进行排序
		  */
		 List<Integer> intList = new ArrayList<>();
		 intList.add(number1);

		 //数量统计
		 TbStockMinuteCountVo countVo1 = new TbStockMinuteCountVo( "9:30",number1,df.format((float) number1 / sum),9);
		 TbStockMinuteCountVo countVo2 = new TbStockMinuteCountVo("10:00",number2,df.format((float) number2 / sum),8);
		 TbStockMinuteCountVo countVo3 = new TbStockMinuteCountVo("10:30",number3,df.format((float) number3 / sum),7);
		 TbStockMinuteCountVo countVo4 = new TbStockMinuteCountVo("11:00",number4,df.format((float) number4 / sum),6);
		 TbStockMinuteCountVo countVo5 = new TbStockMinuteCountVo("13:00",number5,df.format((float) number5 / sum),5);
		 TbStockMinuteCountVo countVo6 = new TbStockMinuteCountVo("13:30",number6,df.format((float) number6 / sum),4);
		 TbStockMinuteCountVo countVo7 = new TbStockMinuteCountVo("14:00",number7,df.format((float) number7 / sum),3);
		 TbStockMinuteCountVo countVo8 = new TbStockMinuteCountVo("14:30",number8,df.format((float) number8 / sum),2);
		 countVoList.add(countVo1);
		 countVoList.add(countVo2);
		 countVoList.add(countVo3);
		 countVoList.add(countVo4);
		 countVoList.add(countVo5);
		 countVoList.add(countVo6);
		 countVoList.add(countVo7);
		 countVoList.add(countVo8);

		 countVoList1.add(countVo1);
		 countVoList1.add(countVo2);
		 countVoList1.add(countVo3);
		 countVoList1.add(countVo4);
		 countVoList1.add(countVo5);
		 countVoList1.add(countVo6);
		 countVoList1.add(countVo7);
		 countVoList1.add(countVo8);


		 System.out.println("总共:"+list.size());
		 String s1 = JSONObject.toJSONString(countVoList);
		 System.out.println(s1);

		//根据数量排名
		 int couont  =1 ;
		 Map<String,Integer>  map = new HashMap<>();
		 for (TbStockMinuteCountVo tbStockMinuteCountVo : countVoList) {
			 tbStockMinuteCountVo.setTop(couont);
			 couont++ ;
			 map.put(tbStockMinuteCountVo.getDayTime(),tbStockMinuteCountVo.getTop());
		 }

		 for (TbStockMinuteCountVo tbStockMinuteCountVo : countVoList1) {
			 String dayTime = tbStockMinuteCountVo.getDayTime();
			 Integer integer = map.get(dayTime);
			 tbStockMinuteCountVo.setTop(integer);
		 }


		 return countVoList1;


	 }

	 public boolean test(int x){
		 if (x%2==0) {
//            System.out.println("x是偶数呢");
			 return false;

		 } else {
//            System.out.println("x是奇数呢~");
			 return  true;
		 }

	 }


	 /**
      * 通过excel导入数据
    *
    * @param request
    * @param response
    * @return
    */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, TbStockK.class);
    }

}
